//
//  ZTSelectCarController.m
//  app001
//
//  Created by xionghao on 15/10/14.
//  Copyright © 2015年 xionghao. All rights reserved.
//

#import "ZTSelectCarController.h"
#import "Puser.h"
#import "ZTCarTableViewCell.h"
#import <MJRefresh.h>
#import "ZCModel.h"
#import "CZSearchBar.h"
@interface ZTSelectCarController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *leftbtn;
@property (weak, nonatomic) IBOutlet UIButton *rightbtn;
@property (nonatomic,strong) Puser *user;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *datalist;
@property (nonatomic,copy) NSString *keyword;
@property (nonatomic,strong) CZSearchBar *search;
@property (nonatomic,assign) BOOL can_add;
@property (nonatomic,assign) NSInteger count;
@property (nonatomic,assign) BOOL isALL;
@end

@implementation ZTSelectCarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setuptableView];
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 46, 0);
    self.tableView.rowHeight=112;
    [self addObserver:self forKeyPath:@"can_add" options:NSKeyValueObservingOptionNew context:nil];
    self.navigationItem.title=@"选择展车";
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(rigthclick)];
    
    
    // Do any additional setup after loading the view from its nib.
}

-(void)rigthclick{
    NSMutableArray *marray=[NSMutableArray array];
    for (ZCModel *mode in self.datalist) {
        if (mode.ischecked) {
            [marray addObject:mode];
        }
    }
    if ([_delegate respondsToSelector:@selector(SelectedCarList:)]) {
        [_delegate SelectedCarList:marray];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"can_add"]) {
        self.leftbtn.enabled=self.can_add;
        [self updatecount];
    }
}

-(void)dealloc{
    [self removeObserver:self forKeyPath:@"can_add"];
}

-(void)updatecount{
    NSInteger count=0;
    for (ZCModel *mode in self.datalist) {
        if (mode.ischecked) {
            count++;
        }
    }
    if (count==self.datalist.count) {
        self.isALL=YES;
    }else{
        self.isALL=NO;
    }
    [self.leftbtn setTitle:[NSString stringWithFormat:@"已选(%ld)",count] forState:UIControlStateNormal];
}

-(void)setuptableView{
    MJRefreshNormalHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.header=header;
    self.tableView.header.automaticallyChangeAlpha=YES;
    MJRefreshBackNormalFooter *footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget: self refreshingAction:@selector(loadmoredata)];
    self.tableView.footer=footer;
    [self.tableView.header beginRefreshing];
    
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)refresh{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
        
        NSInteger power=[self.user.power integerValue];
        
        if (power<5) {
            params[@"type"]=@"person";
            params[@"user_id"]=self.user.user_id;
        }else{
            params[@"type"]=@"company";
            params[@"user_id"]=self.user.com_id;
            //        if (power==8) {
            //            params[@"pid"]=self.user.parent_id;
            //        }
        }
    
    
    if (self.keyword) {
        self.search.text=self.keyword;
        params[@"keyword"]=self.keyword;
        
        params[@"action"]=@"display_search";
    }else{
        
        params[@"action"]=@"display_list";
    }
    params[@"num"]=Kpagesize;
    [PostUitls Post:myzturl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            [self.datalist removeAllObjects];
            
            NSDictionary *data=dict[@"data"];
            
            [ZCModel setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{
                         @"ID" : @"id"
                         };
            }];
            
            NSArray *array=[ZCModel objectArrayWithKeyValuesArray:data[@"list"]];
            
            
            [self.datalist addObjectsFromArray:array];
            if (array.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            self.can_add=NO;
            self.leftbtn.enabled=NO;
            [self.leftbtn setTitle:@"已选(0)" forState:UIControlStateNormal];
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadmoredata{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    

        
        NSInteger power=[self.user.power integerValue];
        if (power<5) {
            params[@"type"]=@"person";
            params[@"user_id"]=self.user.user_id;
        }else{
            params[@"type"]=@"company";
            params[@"user_id"]=self.user.com_id;
            if (power==8) {
                params[@"pid"]=self.user.parent_id;
            }
        }
    
    
    if (self.keyword) {
        params[@"keyword"]=self.keyword;
        params[@"action"]=@"display_search";
    }else{
     
        params[@"action"]=@"display_list";
    }
    
    
    params[@"num"]=Kpagesize;
    NSMutableArray *IDarray=[NSMutableArray array];
    
    for (ZCModel *mode in self.datalist) {
        [IDarray addObject:mode.ID];
    }
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:myzturl parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            
            [ZCModel setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{
                         @"ID" : @"id"
                         };
            }];
            NSDictionary *data=dict[@"data"];
            NSArray *array=[ZCModel objectArrayWithKeyValuesArray:data[@"list"]];
            [self.datalist addObjectsFromArray:array];
            if (array.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            
            [self.tableView reloadData];
            [self updatecount];
            [self.tableView.footer endRefreshing];
        }else{
            [self.tableView.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        [self.tableView.header endRefreshing];
    }];
}


-(NSMutableArray *)datalist{
    if ( _datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return  _datalist;
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.datalist.count==0) {
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }else{
        tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    }
    return self.datalist.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZCModel *mode=self.datalist[indexPath.row];
    mode.ischecked=!mode.ischecked;
    ZTCarTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
    cell.editbutton.selected=!cell.editbutton.selected;
    
    for (ZCModel *carmode in self.datalist) {
        if (carmode.ischecked) {
            self.can_add=YES;
            break;
        }else{
            self.can_add=carmode.ischecked;
        }
    }

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    ZCModel *mode=self.datalist[indexPath.row];

   
    ZTCarTableViewCell *cell=[ZTCarTableViewCell cellWithTableView:tableView];
    cell.mode=mode;
    cell.isShowEidt=YES;
    
    return cell;
}

- (IBAction)btnclick:(UIButton *)sender {
    
    switch (sender.tag) {
        case 0:
            [self selectok];
            break;
        case 1:
            [self allchecked];
            break;
        default:
            break;
    }
    
}

-(void)allchecked{
    self.isALL=!self.isALL;
    for (ZCModel *mode in self.datalist) {
        mode.ischecked=self.isALL;
    }
    self.can_add=self.isALL;
    [self.tableView reloadData];
}

-(void)selectok{
    NSMutableArray *marray=[NSMutableArray array];
    for (ZCModel *mode in self.datalist) {
        if (mode.ischecked) {
            [marray addObject:mode];
        }
    }
    if ([_delegate respondsToSelector:@selector(SelectedCarList:)]) {
        [_delegate SelectedCarList:marray];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
